// pages/shopping/setMeal/purchase.js
const app = getApp()
const connector = require('../../../utils/connector.js')
const format = /^(([1][1-5])|([2][1-3])|([3][1-7])|([4][1-6])|([5][0-4])|([6][1-5])|([7][1])|([8][1-2]))\d{4}(([1][9]\d{2})|([2]\d{3}))(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|([3][0-1]))\d{3}[0-9xX]$/;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    bar_Height: wx.getSystemInfoSync().statusBarHeight + 45,
    array:[
      {id:0,name:"请选择开始生效科目"},
      // {id:1,name:"科一开始生效（未考科一）"},
      // {id:2,name:"科二开始生效（已考科一，未考科二）"},
      // {id:3,name:"科三开始生效（已考科二，未考科三）"},
    ],
    arrIndex:0,
    price:0,
    idcard:'',
  },
  // 选择开始生效科目
  bindPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      arrIndex: e.detail.value
    })
  },
  //信息修改
  edit(e){
    wx.navigateTo({
      url: '/pages/oneself/profile/redact/redact',
    })
  },
  //获取省份证号
  watchPassWord(e){
    console.log(e.detail.value);
    this.setData({
      idcard:e.detail.value
    })
  },
  //立即购买
  payment(e){
    let that = this
    let arrs = [{
      count:1,
      product_id:app.taocanId,
      type:2
    }]
    let users = that.data.user
    let idcard = that.data.idcard
    if(!users.realname || !users.phone || !users.mail_address || !users.school){
      wx.showModal({
        content: '检测到您还没完善个人信息，是否去完善？',
        confirmText: "确认",
        cancelText: "取消",
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/oneself/profile/redact/redact',
            })
          } else {
            wx.switchTab({
              url: '/pages/shopping/shopping',
            })
          }
        }
      });
      return false;
    }
    if (idcard == '') {
      wx.showToast({
        title: "请输入18位身份证号码",
        icon: 'none',
        duration: 1000
      })
      return false
    }else{
      if (idcard.length < 18 || !format.test(idcard)) {
        wx.showToast({
          title: "身份证号输入有误",
          icon: 'none',
          duration: 1000
        })
        return false
      }
    }
    if(that.data.arrIndex == 0){
      wx.showToast({
        title: "请选择开始生效科目",
        icon: 'none',
        duration: 1000
      })
      return false;
    }
    vipUserStatus(that)
    wx.request({
      url: app.conUser + '/order/place',
      data: {
        order_type:2,
        products: arrs,
      },
      header: {
        token: app.tokens
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      success: function (res) {
        // console.log(res)
        if(res.data.order_id > 0){
          wx.setStorageSync('order_id', res.data.order_id);
          // console.log(res.data.order_id)
          // console.log(res.data)
          if (app.tokens) {
            //拉取微信支付
            wx.request({
              url: app.conUser + '/pay/pre_order',
              method: 'POST',
              header: {
                token: app.tokens
              },
              data: {
                id: res.data.order_id
              },
              success: function (ser) {
                // console.log(ser)
                var preData = ser.data;
                // console.log(preData)
                //拉取微信支付
                wx.requestPayment({
                  timeStamp: preData.timeStamp.toString(),
                  nonceStr: preData.nonceStr,
                  package: preData.package,
                  signType: preData.signType,
                  paySign: preData.paySign,
                  success: function (sss) {
                    // console.log(sss)
                    userIfo(that)
                    wx.switchTab({
                      url: '/pages/shopping/shopping',
                    })
                  },
                  fail: function (error) {
                    wx.showToast({
                      title: "下单失败,请重试",
                      icon: 'none',
                      duration: 1000
                    })
                  }

                })

              }
            })
          }
        }else{
          wx.showToast({
            title: "下单失败,请联系客服",
            icon: 'none',
            duration: 1000
          })
        }
        
      },
      fail: function (res) {
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    let parameter = app.globalData.parameter
    let array = [{id:0,name:"请选择开始生效科目"}]
    for(let i = 0;i<parameter.length;i++){
      if(parameter[i] == 1){
        array.push( {id:1,name:"科一开始生效（未考科一）"})
      }
      if(parameter[i] == 2){
        array.push( {id:2,name:"科二开始生效（已考科一，未考科二）"})
      }
      if(parameter[i] == 3){
        array.push( {id:3,name:"科三开始生效（已考科二，未考科三）"})
      }
    }
    // console.log(parameter)
    // console.log(array)
    that.setData({
      array:array
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    vipUserGet(this)
    
    console.log(app.taocanId)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      price:app.taocanPrice
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
   onPullDownRefresh: function () {
    var that = this
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新

  },

})

//获取用户信息
function vipUserGet(that){
  if(wx.getStorageSync("users")){
    // console.log(wx.getStorageSync("users"))
    that.setData({
      user:wx.getStorageSync("users")
    })
  }else{
    connector.getFunc(connector.connector().vipUserGet, "", "get", app.tokens, function (res) {
      // console.log(res)
      if (res.data.result.length < 1) {
      }else{
        wx.setStorageSync("users",res.data.result[0])
        that.setData({
          user:res.data.result[0]
        })
      }
    }, function (res) {
      wx.showToast({
        title: "内部错误",
        icon: 'none',
        duration: 1000
      })
    })
  }
}
//购买保险
function vipUserStatus(that){
    let obj = {
      vip:{
        id:wx.getStorageSync("users").id,
        type:that.data.arrIndex,
        idcard:that.data.idcard
      }
    }
    // console.log("购买保险:" + JSON.stringify(obj))
    connector.getFunc(connector.connector().vipUserStatus, obj, "post", app.tokens, function (res) {
      // console.log(res)
     
    }, function (res) {
      wx.showToast({
        title: "内部错误",
        icon: 'none',
        duration: 1000
      })
    })
  // }
}
//获取个人信息
function userIfo(that){
  // vip_status是否购买理赔；0：未购买；1：科目一
  connector.getFunc(connector.connector().userIfo, "", "get", app.tokens, function (res) {
    // console.log(res)
    if (res.statusCode == 200) {
      let identity = false
      wx.setStorageSync("userInfo",res.data.user_info)
      let myId;
      // console.log(res.data.user_info.user_id)
      if(res.data.user_info.coach){
        identity = true
        myId = res.data.user_info.user_id
      }else{
        myId = res.data.user_info.pid
        identity = false
      }
      app.globalData.myId = myId
      app.globalData.identity = identity
      app.globalData.identitys = "yes"
      app.globalData.isYes = true
    }
  }, function (res) {
    wx.showToast({
      title: "内部错误",
      icon: 'none',
      duration: 1000
    })
  })
}
